//
//  BCNoteDisplayViewController.m
//  Memo
//
//  Created by 李雪 on 16/3/6.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.//

#import "BCNoteDisplayViewController.h"
#import "BCDateBase.h"
#import "BCAddNoteViewController.h"
#import "BCNoteCell.h"
#import "BCNoteUpdateViewController.h"

@interface BCNoteDisplayViewController ()
@property (strong,nonatomic) UITableView* mytable;
@property (strong,nonatomic) NSMutableArray* memos;
@property (strong,nonatomic) UILabel* contentLabel;
@end

@implementation BCNoteDisplayViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title=@"日程列表";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    if (IOS_VERSION_Above_7_0) {
//        self.edgesForExtendedLayout=UIRectEdgeNone;
//    }
	// Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    self.mytable=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-44) style:UITableViewStylePlain];
    self.mytable.delegate=self;
    self.mytable.dataSource=self;
    [self.view addSubview:self.mytable];
    
    NSDateFormatter* formatter=[[NSDateFormatter alloc]init];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-3600*8]];
     [formatter setCalendar:[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateStr=[NSString stringWithFormat:@"%@ 00:00:00",[formatter stringFromDate:self.date]];
    
    NSDateFormatter* formatter1=[[NSDateFormatter alloc]init];
    [formatter1 setTimeZone:[NSTimeZone defaultTimeZone]];
    [formatter1 setCalendar:[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]];
    [formatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate* newDate=[formatter1 dateFromString:dateStr];
    
    if ([newDate timeIntervalSince1970]>[[NSDate date] timeIntervalSince1970]||[[NSDate date] timeIntervalSince1970]-[newDate timeIntervalSince1970]<=24*3600) {
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewMemo)];
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.memos=[[NSMutableArray alloc]initWithArray:[[BCDateBase defaultBase] allNotesOnDate:_date]];
    [self.mytable reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark
#pragma mark TableView Delegate Method and TableView DataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.memos count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 82.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* idetifier=@"EventCell";
    BCNoteCell* cell=[tableView dequeueReusableCellWithIdentifier:idetifier];
    
    if (!cell) {
        cell=[[BCNoteCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:idetifier];
    }
    
    NSDictionary* note=[self.memos objectAtIndex:indexPath.row];
    NSDate* noteTime=[note valueForKey:kDateKey];
    NSCalendar* cal=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comp=[[NSDateComponents alloc]init];
    [comp setHour:8];
    NSDate* ealierDate=[noteTime earlierDate:[cal dateByAddingComponents:comp toDate:[NSDate date] options:0]];
    if (ealierDate==[note valueForKey:kDateKey]) {
        cell.backgroundImageView.image=[UIImage imageNamed:@"cellBG1.jpg"];
    }else cell.backgroundImageView.image=[UIImage imageNamed:@"cellBG2.jpg"];
    
    [comp setHour:-8];
    noteTime=[cal dateByAddingComponents:comp toDate:noteTime options:0];
    NSDateFormatter* fm=[[NSDateFormatter alloc]init];
    [fm setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString* noteTimeStr=[fm stringFromDate:noteTime];
    cell.timeLabel.text=noteTimeStr;
    
    cell.contentLabel.text=[note valueForKey:kContentKey];
    UILongPressGestureRecognizer* longPressGR=[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressOnCell:)];
    [cell addGestureRecognizer:longPressGR];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary* note=[self.memos objectAtIndex:indexPath.row];
    BOOL result=[[BCDateBase defaultBase] deleteANoteOnTime:[note valueForKey:kDateKey] withContent:[note valueForKey:kContentKey] AlertMode:[((NSNumber*)[note valueForKey:kAlertMode]) integerValue]];
    if (result) {
        [self.memos removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:YES];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary* dic=[self.memos objectAtIndex:indexPath.row];
    NSDate* date=[dic valueForKey:kDateKey];
    NSString* content=[dic valueForKey:kContentKey];
    BCAlertMode alertMode=[((NSNumber*)[dic valueForKey:kAlertMode]) integerValue];
    BCNoteUpdateViewController* noteUpdateVC=[[BCNoteUpdateViewController alloc]initWithTime:date Content:content andAlertMode:alertMode];
    [self.navigationController pushViewController:noteUpdateVC animated:YES];
}

#pragma mark

-(void)dismiss
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addNewMemo
{
    NSDateFormatter* formatter=[[NSDateFormatter alloc]init];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-3600*8]];
    [formatter setCalendar:[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateStr=[NSString stringWithFormat:@"%@ 00:00:00",[formatter stringFromDate:self.date]];
    NSDateFormatter* formatter1=[[NSDateFormatter alloc]init];
    [formatter1 setTimeZone:[NSTimeZone defaultTimeZone]];
    [formatter1 setCalendar:[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]];
    [formatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate* newDate=[formatter1 dateFromString:dateStr];
    
    BCAddNoteViewController* addVC=[[BCAddNoteViewController alloc]init];
    if ([newDate timeIntervalSince1970]>[[NSDate date] timeIntervalSince1970]) {
        addVC.chosenTime=newDate;
    }else if ([[NSDate date] timeIntervalSince1970]-[newDate timeIntervalSince1970]<=24*3600){
        addVC.chosenTime=[NSDate date];
    }
    [self.navigationController pushViewController:addVC animated:YES];
}

#pragma mark
#pragma mark Settor
-(void)setDate:(NSDate *)date
{
    _date=date;
    self.memos=[NSMutableArray arrayWithArray:[[BCDateBase defaultBase] allNotesOnDate:date]];
    NSLog(@"date=%@;array=%@",self.date,self.memos);
}

-(void)longPressOnCell:(id)sender
{
    UILongPressGestureRecognizer* longPressGR=sender;
    BCNoteCell* cell=(BCNoteCell*)longPressGR.view;
    NSString* text=cell.contentLabel.text;
    if (!self.contentLabel) {
        self.contentLabel=[[UILabel alloc]init];
        self.contentLabel.backgroundColor=[UIColor colorWithRed:0 green:0 blue:1 alpha:0.4];
        self.contentLabel.layer.cornerRadius=10.0f;
        self.contentLabel.numberOfLines=0;
        self.contentLabel.lineBreakMode=UILineBreakModeWordWrap;
        self.contentLabel.userInteractionEnabled=YES;
        UITapGestureRecognizer* tapGR=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissContentLabel:)];
        [self.contentLabel addGestureRecognizer:tapGR];
    }
        if (self.contentLabel.superview) {
            [self.contentLabel removeFromSuperview];
        }
    
    CGSize tempSize=[text sizeWithFont:self.contentLabel.font constrainedToSize:CGSizeMake(280, 160)];
    self.contentLabel.frame=CGRectMake(0, 0, tempSize.width, tempSize.height);
    self.contentLabel.text=text;
    self.contentLabel.center=CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2-self.contentLabel.bounds.size.height/2);
    [self.view addSubview:self.contentLabel];
}

-(void)dismissContentLabel:(UITapGestureRecognizer*) tapGR
{
    [self.contentLabel removeFromSuperview];
}

@end
